package cc.booku.owlbox.DataAcquisition;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

public class TextSView extends AppCompatTextView {
    /**
     * 时间步
     */
    public static final float TIME_STEP = 1f / 50f;

    private Runnable mTicker;
    private Handler mHandler;

    private boolean mTickerStopped = false;

    private int count = 1;

    public TextSView(Context context) {
        super(context);
    }

    public TextSView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        mTickerStopped = false;
        super.onAttachedToWindow();
        mHandler = new Handler();

        /**
         * requests a tick on the next hard-second boundary
         */
        mTicker = new Runnable() {
            public void run() {
                if (mTickerStopped) {
                    return;
                }

                setText("count:" + count++);
                invalidate();

                long next = SystemClock.uptimeMillis() + (long) (TIME_STEP * 1000);
                mHandler.postAtTime(mTicker, next);
            }
        };
        mTicker.run();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mTickerStopped = true;
    }
}